;(function($, window, document, undefined){
	var counter = 0;
	var line = 0;
	var initPosition = 100;
	var hasMovingSticker = false;
	var defaults = {
		width: '200px',
		height: '200px',
		color : '',
		saveStickerCallback : null,
		closeStickerCallback : null
 	}
	
	function Sticker(element,options,stickers){
		this.element = $(element);
		this.options = $.extend({}, defaults, options);
		this.init(stickers);
	}
	Sticker.prototype = {
		init : function(existStickers){
			this._createAddingBtn();
			if(existStickers && existStickers.length>0){
				this.loadExistStickers(existStickers);
			}
		},
		loadExistStickers : function(existStickers){
			for(var i=0;i<existStickers.length;i++){
				var stickerEl = document.createElement('div');
				stickerEl.className = 'sticker ' + this.options.color;
				stickerEl.style.width = existStickers[i].width||this.options.width; //带着px
				stickerEl.style.height = existStickers[i].height||this.options.height; //带着px
				stickerEl.style.left =  existStickers[i].left;
				stickerEl.style.top = existStickers[i].top;
				stickerEl.setAttribute('createTime',existStickers[i].createTime);
				stickerEl.setAttribute('stickerId',existStickers[i].stickerId);
				this._addChild(stickerEl, this);
				
				stickerEl.lastElementChild.value = existStickers[i].content;
				
			}
		},
		_addChild : function(stickerEl, obj, add) { //添加子类元素
			bindResize(stickerEl); //div resize
			var tape = document.createElement('div');
			tape.className = 'tape';
			var createTime = stickerEl.getAttribute("createTime");
			if (!createTime) {
				createTime = dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
            }
			tape.innerHTML = "<div class='tape-tc titleContainer'><div class='tape-t title'>"+createTime+"</div></div>";
			var stickerTA = document.createElement('textarea');
			stickerTA.className = 'show-content'; //增加样式
			if(add){
				$(stickerTA).html("注意保存（系统不会自动保存）！");
			}
			
			var closeBtn = $('<button type="button" class="close-btn" title="关闭">×</button>');
			var saveBtn = $('<button type="button" class="save-btn" title="保存"></button>');
			var tdBtn = $('<span class="td"> </span>');
			var dragBtnRB = $('<button type="button" class="drag-btn drag-btn-rightbottom" title="拖动改变大小"></button>');
			var dragBtnLB = $('<button type="button" class="drag-btn drag-btn-leftbottom" title="拖动改变大小"></button>');
			var dragBtnRC = $('<button type="button" class="drag-btn drag-btn-rightcenter" title="拖动改变大小"></button>');
			stickerEl.appendChild(closeBtn[0]);
			stickerEl.appendChild(saveBtn[0]);
			stickerEl.appendChild(tdBtn[0]);
			stickerEl.appendChild(dragBtnRB[0]);
			stickerEl.appendChild(dragBtnLB[0]);
			stickerEl.appendChild(dragBtnRC[0]);
			stickerEl.appendChild(tape);
			stickerEl.appendChild(stickerTA);
			document.getElementsByTagName('body')[0].appendChild(stickerEl);
			
			$(stickerEl.childNodes[0]).on('click', obj, obj.closeSticker);
			$(stickerEl.childNodes[1]).on('click', obj, obj.saveSticker);
			if(add){
				counter++;
			}
			$(stickerEl).on('mousedown', obj._dragSticker);
			$(window).on('mousemove', obj._moveSticker);
			$(window).on('mouseup', obj._dropSticker);
			
        },
		_createAddingBtn : function(){
			var addingBtn = document.createElement('div');
			addingBtn.className = 'sticker-adding-btn';
			addingBtn.appendChild(document.createTextNode('+'));
			document.getElementsByTagName('body')[0].appendChild(addingBtn);
			$(addingBtn).on('click', this, this._createSticker);
			

		},
		_createSticker : function(event){
			var Sticker = event.data;
			var stickerEl = document.createElement('div');
			var stickerWidth = Number(Sticker.options.width.replace('px',''));
			var stickerHeight = Number(Sticker.options.height.replace('px',''));
			stickerEl.className = 'sticker ' + Sticker.options.color;
			if((document.body.clientWidth + document.body.scrollLeft) - counter*(stickerWidth+40) < (stickerWidth+40)){
				counter = 0;
				line++;
			} 
			stickerEl.style.width = Sticker.options.width;
			stickerEl.style.height = Sticker.options.height;
			stickerEl.style.left = initPosition + counter*(stickerWidth+40) + 'px';
			stickerEl.style.top = initPosition + line*(stickerHeight+40) + 'px';
			Sticker._addChild(stickerEl, Sticker, true);
		},
		_dragSticker : function(event){ //鼠标按下
			
			if(event.target.className.indexOf('tape') != -1 && !this.moving){
				
				//this.clientX = event.clientX + (document.body.scrollLeft || document.documentElement.scrollLeft);
				//this.clientY = event.clientY + (document.body.scrollTop || document.documentElement.scrollTop); 
				//this.style.left = this.clientX + 'px';
				//this.style.top = this.clientY + 'px';
				this.moving = true;
				this.style.cursor = 'pointer';
				//$(this).find(".show-content").css('cursor', 'move');
				hasMovingSticker = true;
				$(this).data("drag", true); //标识拖拽
				$(this).attr("drag", true); //标识拖拽
			}
			document.onselectstart=new Function("event.returnValue=false;"); //移动时不可选后面的文字
		},
		_moveSticker : function(event){
			if(hasMovingSticker){
				var targetE = $(event.target);
				if (targetE.hasClass("show-content")) {
					console.log("textarea==="+event.target.outerHTML)
                }
				var stickers = $('.sticker');
				for(var i=0;i<stickers.length;i++){
					if(stickers[i].moving){
						event.preventDefault();
						var newClientX = event.clientX + (document.body.scrollLeft || document.documentElement.scrollLeft),
						newClientY = event.clientY + (document.body.scrollTop || document.documentElement.scrollTop);
						var left = parseInt(stickers[i].style.left) || 0;
						var top = parseInt(stickers[i].style.top) || 0;
						var stickersLeft = left + (newClientX - stickers[i].clientX);
						var stickersTop = top + (newClientY - stickers[i].clientY);
						if (stickersLeft <= 0) { //不能超出边界
							stickersLeft = 0;
							newClientX = stickers[i].clientX;
                        }
						if (stickersTop <= 0) {
							stickersTop = 0;
							newClientY = stickers[i].clientY;
                        }
						if (newClientX <= 0) { //不能超出边界
							newClientX = 0;
                        }
						if (newClientY <= 0) {
							newClientY = 0;
                        }
						// console.log(" stickersLeft="+stickersLeft+" stickersTop="+stickersTop+" newClientX="+newClientX+" newClientY="+newClientY
								// +" event.clientX="+event.clientX+" event.clientY="+event.clientY)
						stickers[i].style.left = stickersLeft + 'px';
						stickers[i].style.top = stickersTop + 'px';
						stickers[i].clientX = newClientX; //记录上次鼠标位置
						stickers[i].clientY = newClientY; //记录上次鼠标位置
					}
				}
			}
			

		},
		_dropSticker : function(event){ //s
			if(hasMovingSticker){
				var stickers = $('.sticker');
				for(var i=0;i<stickers.length;i++){
					if(stickers[i].moving){
						var clientX = event.clientX;
						var clientY = event.clientY;
						stickers[i].style.left = stickers[i].clientX = clientX;  
						stickers[i].style.top = stickers[i].clientY = clientY; 
						stickers[i].style.cursor = 'none';
						stickers[i].moving = false; 
						$(stickers[i]).removeAttr("drag"); //标识拖拽完成
						$(stickers[i]).removeData("drag"); //标识拖拽完成
					}
				}
				hasMovingSticker = false;

			}
			document.onselectstart=new Function("event.returnValue=true;"); //移动完成后，document的内容恢复可选
		},
		closeSticker : function(event){
			var Sticker = event.data;
			if($.isFunction(Sticker.options.closeSticker)) {
				Sticker.options.closeSticker(this.parentElement.getAttribute('stickerId'), this.parentElement);
			} else {
				if($.isFunction(Sticker.options.closeStickerCallback)) {
					Sticker.options.closeStickerCallback.call(this, this.parentElement.getAttribute('stickerId'));
				}
				this.parentElement.remove();
			}
		},
		saveSticker : function(event){
			var Sticker = event.data;
			var stickerEl = this.parentElement;
			if($.isFunction(Sticker.options.saveStickerCallback)) {
							var stickerItem = {
								left : stickerEl.style.left,
								top : stickerEl.style.top,
								content : this.parentElement.lastElementChild.value,
								stickerId : this.parentElement.getAttribute('stickerId')
							} 
							Sticker.options.saveStickerCallback.call(this, stickerItem);
						}
		}

	}

	$.fn.sticker = function(options, stickers){
		new Sticker(this,options, stickers);
	}
	function bindResize(el){
        //初始化参数 
        var els = el.style, 
            //鼠标的 X 和 Y 轴坐标 
            x = y = 0;
        $(el).mousemove(function(e) {
        	if (!$(el).data("drag")) {
        		var $this = $(this);
        		var showContentE = $this.find(".show-content");
        		var left = $this.offset().left;
        		var top = $this.offset().top;
//        		var width = $this.width(); //只是获取content宽度
        		var width = $this.innerWidth();//获取content+padding的宽度
//        		var withoutMargin = $this. outerWidth();//获取content+padding+border的宽度
//        		var full = $this. outerWidth(true);//获取content+padding+border+margin的宽度
        		
//        		var height = $this.height();
        		var height = $this.innerHeight();//获取content+padding的宽度
//        		console.log(e.clientX+" "+e.clientY+" "+width+" "+height);
        		var xval = e.clientX - left;
        		var yval = e.clientY - top;
//        		console.log(" xval="+xval+" yval="+yval+" w="+width+" "+height);
//        		console.log(" height-yval="+(height-yval)+" width-xval="+ (width-xval) +" "+ xval);
        		// 右上角
        		if (width-xval <= 10 && yval<=10 ) {
        			$this.css('cursor', 'ne-resize');
        			showContentE.css('cursor', 'ne-resize');
        			$this.data("resize",true);
        		} else if (width-xval <= 20 && yval >50 && height-yval > 50) { // 右侧
        			$this.css('cursor', 'w-resize');
        			showContentE.css('cursor', 'w-resize');
        			$this.data("resize",true);
        		} else if (height-yval <=10 && width-xval <= 10) { // 右下角
        			$this.css('cursor', 'se-resize');
        			showContentE.css('cursor', 'se-resize');
        			$this.data("resize",true);
        		} else if (height-yval <=10 && width-xval>50 && xval >50) { // 下
        			$this.css('cursor', 's-resize');
        			showContentE.css('cursor', 's-resize');
        			$this.data("resize",true);
        		} else if (height-yval <=10 && xval <= 10) { // 左下角
        			$this.css('cursor', 'ne-resize');
        			showContentE.css('cursor', 'ne-resize');
        			$this.data("resize",true);
        		}
//            else if (xval <= 40 && height-yval>50 && yval>50) { // 左
//            	showContentE.css('cursor', 'w-resize');
//            	$this.data("resize",true);
//            } else if (xval <=40 && yval <= 30) { // 左上角
//            	showContentE.css('cursor', 'se-resize');
//            	$this.data("resize",true);
//            }
        		else { // 中间位置
        			$this.css('cursor', 'default');
        			showContentE.css('cursor', 'default');
        			$this.removeData("resize");
        		}
        	}
        })
        //邪恶的食指
        $(el).mousedown(function(e){
        	//只有在拖拽图标操作时才生效
        	if($(el).data("resize")){
        		$(el).css("cursor", "move");//改变鼠标指针的形状
        		$(el).data("drag", true);
        		$(el).attr("drag", true);
        		//按下元素后，计算当前鼠标与对象计算后的坐标 
        		x = e.clientX - el.offsetWidth, 
        		y = e.clientY - el.offsetHeight; 
        		//在支持 setCapture 做些东东 
        		el.setCapture ? ( 
        				//捕捉焦点 
        				el.setCapture(), 
        				//设置事件 
        				el.onmousemove = function(ev){ 
        					mouseMove(ev || event) 
        				}, 
        				el.onmouseup = mouseUp 
        		) : ( 
        				//绑定事件 
        				$(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp) 
        		) 
        		//防止默认事件发生 
        		e.preventDefault();
			}
        });
        //移动事件 
        function mouseMove(e){
            //宇宙超级无敌运算中... 
            els.width = e.clientX - x + 'px', 
            els.height = e.clientY - y + 'px' 
        }
        //停止事件 
        function mouseUp(){
        	$(el).removeData("drag");
        	$(el).removeAttr("drag");
        	$(el).removeData("resize");
            //在支持 releaseCapture 做些东东 
            el.releaseCapture ? ( 
                //释放焦点 
                el.releaseCapture(), 
                //移除事件 
                el.onmousemove = el.onmouseup = null 
            ) : ( 
                //卸载事件 
                $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp) 
            )
        }
    }

})(window.jQuery, window, document);